package net.hyperz.showtime.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.nio.ByteBuffer;

import org.jsoup.connect.Connection;
import org.jsoup.helper.HttpConnection;
import org.jsoup.helper.HttpConnection.ProxyAuthenticator;
import org.jsoup.nodes.Document;

import android.graphics.Bitmap;

public abstract class HttpLoad {
	private final static String PROXY_HOST = "internet2.can.eds.com";
	private final static int PROXY_PORT = 8080;
	private final static String PROXY_UID = "siegleda";
	private final static String PROXY_PWD = "Calgary99!";
	
	public static boolean useProxy = true;
	
	public static Document getDocument(String url, String... keyvals) throws IOException {
		try {

			Connection jsConn = HttpConnection.connect(url);
			
			if (useProxy)
				((HttpConnection) jsConn).proxy(PROXY_HOST, PROXY_PORT, PROXY_UID, PROXY_PWD);
			
			jsConn.timeout(6000);
			jsConn.userAgent("Mozilla");
			jsConn.data(keyvals);
System.err.println("Getting Data");
			return jsConn.get();
		} catch (IOException e) {
			throw e;
		}
	}
	
	public static byte[] LoadImage(String URL)
	{     
		byte[] buffer = new byte[0x20000];
		ByteBuffer byteData = null;
		Proxy proxy = null;
		URL url;
		
		try {
			url = new URL(URL);
			
			if (useProxy) {
				Authenticator.setDefault(new ProxyAuthenticator(PROXY_UID, PROXY_PWD));
	        	proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_HOST, PROXY_PORT));
			}
			
			HttpURLConnection conn = (useProxy) ? (HttpURLConnection) url.openConnection(proxy) : (HttpURLConnection) url.openConnection();
			
			InputStream in = conn.getInputStream();
			
            ByteArrayOutputStream outStream = new ByteArrayOutputStream(0x20000);
            int read;
            while(true) {
                read  = in.read(buffer);
                if (read == -1) break;
                outStream.write(buffer, 0, read);
            }
            byteData = ByteBuffer.wrap(outStream.toByteArray());
            
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			
		return byteData.array();         
	}
	
	public static byte[] ConvertImage(Bitmap bitmap) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();  
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);   
		return baos.toByteArray(); 
	}
}
